package com.tiza.xiaoyoubao.ui.fragment;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.BuyerMoneyInfo;
import com.tiza.xiaoyoubao.entity.DateInfo;
import com.tiza.xiaoyoubao.entity.IdCardInfo;
import com.tiza.xiaoyoubao.entity.NewGudieInfo;
import com.tiza.xiaoyoubao.entity.NewsInfo;
import com.tiza.xiaoyoubao.entity.TaoBaoAccountInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.entity.bean.BankInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.DateUtils;
import com.tiza.xiaoyoubao.utils.UpdateManger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by mapple on 17/2/17.
 */

public class MainFragment extends BaseFragment {

    @BindView(R.id.lv_listView)
    ListView mListView;
    @BindView(R.id.view_commission)
    View view_commission;
    @BindView(R.id.view_principal)
    View view_principal;
    @BindView(R.id.view_gonggao)
    View view_gonggao;
    @BindView(R.id.tv_gonggao)
    TextView tv_gonggao;
    //佣金
    @BindView(R.id.tv_commission)
    TextView tv_commission;
    //本金
    @BindView(R.id.tv_principal)
    TextView tv_principal;
    private List<NewGudieInfo> mList;
    private MyAdapter mAdapter;
    private DateInfo dateInfo;
    private List<TaoBaoAccountInfo> mList2 = new ArrayList<>();
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_layout;
    }

    @Override
    protected void initData() {
        getBuyerMoney();
        getUpdate();
        getNews();
    }

    @Override
    protected void initView() {
        setToolbarTitle("小优宝");
        mList = new ArrayList<>();
        mList.add(new NewGudieInfo(1, R.mipmap.newcourse, "新手教学", "学习新手教学后再做任务"));
        //mList.add(new NewGudieInfo(1, R.mipmap.newcourse, "新手教学", "学习新手教学后再做任务"));
        mList.add(new NewGudieInfo(3, R.mipmap.advancestask, "垫付任务", "最稳定收入来源,每日必做"));
        mList.add(new NewGudieInfo(3, R.mipmap.browse_makemoney, "浏览任务", "最稳定收入来源,每日必做"));
        // mList.add(new NewGudieInfo(1, R.mipmap.sendorders_task, "派单任务", "最稳定收入来源,每日必做"));
        mList.add(new NewGudieInfo(1, R.mipmap.generalize_makemoney, "推广赚金", "邀请一个好友可得5元现金"));
        mList.add(new NewGudieInfo(1, R.mipmap.wentifankui, "问题反馈", "有问题可及时反馈给平台，平台一对一回答"));
        mAdapter = new MyAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 3) {
                    UIHelper.showPromoteMakeMoney(mActivity);
                } else if (i == 1) {
                  //UIHelper.showDianFuMakeMoney(mActivity);
                    getBuyerIdCard();
                } else if (i == 2) {
//                    toast("功能部署中，敬请期待");
                    UIHelper.showBrowseMakeMoney(mActivity);
                } else if (i == 0) {
                    UIHelper.showNewTeach(mActivity);
                } else {
                    toast("功能部署中，敬请期待");
                }
            }
        });
    }


    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.recycle_item, null);
                holder = new ViewHolder();
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_newTask);
                holder.tvContent = (TextView) convertView.findViewById(R.id.tv_newTask_Content);
                holder.mImageView = (ImageView) convertView.findViewById(R.id.imageView);
                holder.tvNews = (TextView) convertView.findViewById(R.id.tv_news);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvTitle.setText(mList.get(position).getTitle());
            holder.tvContent.setText(mList.get(position).getConnect());
            holder.mImageView.setImageResource(mList.get(position).getImage());
            if (mList.get(position).getId() == 1) {
                holder.tvNews.setText("");
            } else if (mList.get(position).getId() == 3) {
                holder.tvNews.setText("( 99 )");
            }
            return convertView;
        }
    }

    static class ViewHolder {
        public TextView tvTitle;
        public TextView tvContent;
        public TextView tvNews;
        public ImageView mImageView;
    }

    @OnClick({R.id.view_commission, R.id.view_principal, R.id.view_gonggao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_commission:
                UIHelper.showCommission(mActivity);
                break;
            case R.id.view_principal:
                UIHelper.showPrincipal(mActivity);
                break;
            case R.id.view_gonggao:
                UIHelper.showNotice(mActivity);
                break;
        }

    }

    private void getBuyerMoney() {
        ApiHttpClient.getBuyerMoney(MainFragment.this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                                    new JsonCallback<BuyerMoneyInfo>(BuyerMoneyInfo.class) {

                                        @Override
                                        public void onBefore(Request request) {
                                            super.onBefore(request);
                                            showWaitingDialog();
                                        }

                                        @Override
                                        public void onError(Call call, Exception e) {
                                            toast("获取信息失败");
                                        }

                                        @Override
                                        public void onResponse(
                                                ResponseInfo<BuyerMoneyInfo> response
                                        ) {
                                            int code = response.getCode();
                                            String message = response.getMessage();
                                            if (code == 1) {
                                                showWarnDialog(message);
                                                return;
                                            }
                                            List<BuyerMoneyInfo> data = response.getData();
                                            if (null == data || data.size() == 0) {
                                                toast("获取信息失败");
                                                return;
                                            }
                                            BuyerMoneyInfo moneyInfo = data.get(0);
                                            if (moneyInfo == null) {
                                                tv_commission.setText("0.0");
                                                tv_principal.setText("0.0");
                                            } else {
                                                tv_commission.setText(
                                                        DateUtils.formateRate(moneyInfo.getCmi()));
                                                tv_principal.setText(DateUtils.formateRate(
                                                        moneyInfo.getBalance()));
                                            }

                                        }

                                        @Override
                                        public void onAfter() {
                                            super.onAfter();
                                            hideWaitingDialog();
                                        }
                                    }
        );
    }

    private void getUpdate() {
        ApiHttpClient.getVersion(this, new JsonCallback<DateInfo>(DateInfo.class) {

            @Override
            public void onBefore(Request request) {
                super.onBefore(request);
                showWaitingDialog();
            }

            @Override
            public void onError(Call call, Exception e) {
                toast("网络异常请重试");
            }

            @Override
            public void onResponse(ResponseInfo<DateInfo> response) {
                int code = response.getCode();
                String message = response.getMessage();
                if (code == 1) {
                    showWarnDialog(message);
                    return;
                }
                List<DateInfo> data = response.getData();
                if (null == data || data.size() == 0) {
                    toast("获取版本信息失败");
                    return;
                }
                dateInfo = data.get(0);
                String serverVersion = dateInfo.getVersionnumber();
                String path = dateInfo.getVersionurl();
                Log.i("版本", "从服务器获取的版本号是：" + serverVersion + "下载路径：" + path);
                Hawk.put(Constants.KEY_GETUPDATE_INFO, dateInfo);
                new UpdateManger(mActivity).checkUpdate();
            }

            @Override
            public void onAfter() {
                super.onAfter();
                hideWaitingDialog();
            }
        });
    }

    private void getBuyerIdCard() {
        ApiHttpClient.getBuyerIdCard(this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                                     new JsonCallback<IdCardInfo>(IdCardInfo.class) {
                                         @Override
                                         public void onError(Call call, Exception e) {
                                             toast("网络异常，请检查后再试");
                                         }

                                         @Override
                                         public void onResponse(ResponseInfo<IdCardInfo> response) {
                                             int code = response.getCode();
                                             if (code == 1) {
                                                 showWarnDialog(response.getMessage());
                                                 return;
                                             }
                                             List<IdCardInfo> data = response.getData();
                                             if (null == data.get(0) || data.size() == 0) {
                                                 toast("请先绑定身份证");
                                                 return;
                                             }
                                             if(data.get(0).getAuth().equals("1")){
                                                 getBankInfo();
                                             }else {
                                                 toast("请先绑定身份证");
                                             }

                                         }
                                     }
        );
    }

    private void getBankInfo() {
        ApiHttpClient.getBuyerBankInfo(this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                                       new JsonCallback<BankInfo>(BankInfo.class) {
                                           @Override
                                           public void onBefore(Request request) {
                                               super.onBefore(request);
                                           }

                                           @Override
                                           public void onError(Call call, Exception e) {
                                               toast("网络异常,请稍后重试");
                                           }

                                           @Override
                                           public void onResponse(ResponseInfo<BankInfo> response) {
                                               int code = response.getCode();
                                               String message = response.getMessage();
                                               if (code == 1) {
                                                   showWarnDialog(message);
                                                   return;
                                               }
                                               List<BankInfo> data = response.getData();
                                               if (null == data || data.size() == 0) {
                                                   toast("请先绑定银行卡");
                                                   return;
                                               }
                                               getBankTaoBao();
                                           }

                                           @Override
                                           public void onAfter() {
                                               super.onAfter();
                                           }
                                       }
        );
    }

    private void getBankTaoBao() {
        ApiHttpClient.getBuyerTaoBao(this, userInfo.getWebzzCmsBuyerInfo().getUserid(),
                                     new JsonCallback<TaoBaoAccountInfo>(TaoBaoAccountInfo.class) {
                                         @Override
                                         public void onBefore(Request request) {
                                             super.onBefore(request);
                                         }

                                         @Override
                                         public void onError(Call call, Exception e) {
                                             toast("网络异常,请稍后重试");
                                         }

                                         @Override
                                         public void onResponse(
                                                 ResponseInfo<TaoBaoAccountInfo> response
                                         ) {
                                             int code = response.getCode();
                                             String message = response.getMessage();
                                             if (code == 1) {
                                                 showWarnDialog(message);
                                                 return;
                                             }
                                             List<TaoBaoAccountInfo> mList = response.getData();
                                             if (null == mList || mList.size() == 0) {
                                                 toast("请先绑定淘宝号");
                                             } else {
                                                 for (int i = 0; i < mList.size(); i++) {
                                                     if (mList.get(i).getAuth() == 1) {
                                                         mList2.add(mList.get(i));
                                                     }
                                                 }
                                             }
                                             if (mList2.size() > 0) {
                                                 UIHelper.showDianFuMakeMoney(mActivity);
                                             }else {
                                                 toast("请先绑定淘宝号");
                                             }
                                         }

                                         @Override
                                         public void onAfter() {
                                             super.onAfter();
                                         }
                                     }
        );
    }

    private void getNews() {
        ApiHttpClient.getNews(this, new JsonCallback<NewsInfo>(NewsInfo.class) {

            @Override
            public void onBefore(Request request) {
                super.onBefore(request);
                showWaitingDialog();
            }

            @Override
            public void onError(Call call, Exception e) {
                toast("网络异常请重试");
            }

            @Override
            public void onResponse(ResponseInfo<NewsInfo> response) {
                int code = response.getCode();
                String message = response.getMessage();
                if (code == 1) {
                    showWarnDialog(message);
                    return;
                }
                List<NewsInfo> data = response.getData();
                if (null == data || data.size() == 0) {
                    toast("获取版本信息失败");
                    return;
                }
                NewsInfo newsInfo=data.get(0);
                tv_gonggao.setText(newsInfo.getTitle().substring(0,10)+"...");
            }

            @Override
            public void onAfter() {
                super.onAfter();
                hideWaitingDialog();
            }
        });
    }
}
